'''
F频率 T周期
F = 1 / T   PWM计算公式
T = 1 / F

13bit频率为0-100% 8192个电平
B步长
B = T / 8192 
'''
class PWMS:
    '''计算PWM参数'''
    def __init__(self,**kwargs):
        '''接收参数,并初始化'''
        self.bit = kwargs.get("bit",None)
        self.T = kwargs.get("T",None)   #取字典
        self.F = kwargs.get("F",None)
        
    def led_num(self):
        '''计算Pwm离散电平'''
        self.cycle()
        self.ledn = 2**self.bit              #计算出离散电平
        resolution = 100/self.ledn           #计算出分辨率
        B = self.Ti/self.ledn                #一个离散电平所占用的时间
        return self.ledn,B

    def cycle(self):
        '''周期'''
        T = self.T
        F = self.F
        if T:
            F = 1000/T
            output = f"当前1周期:{T}ms/{T*1000}us频率:{F}"
            self.Fs = F                 #Fs频率
            return output               
        if F:
            T = 1000/F
            output = f"当前1周期:{T}ms/{T*1000}us,频率:{F}"
            self.Ti = T                 #Ti周期
            return output               

    def count_steps(self,time_need):
        '''
        # 变量说明
        - time_need:一个pwm周期高电平时间
        - cycle_time:一个pwm周期时间
        - total_steps:精度步数
        ## 计算方法
        计算出所需高电平时间的百分比
        所需步数=所需时间/周期时间*总步数
        steps_need = time_need/cycle_time*total_steps
        '''
        cycle_time = self.Ti*1000*1000  #转化为ns单位
        total_steps = self.ledn
        steps_need = time_need/cycle_time*total_steps
        try:
            #进行保留0位的四舍五入
            steps_need = str(steps_need).split(".")
            if int((steps_need[1])[0])>=5:
                return int(steps_need[0])+1
            else:
                return int(steps_need)
        except:return int(steps_need)
        
if __name__ == "__main__":
    app = PWMS(bit=6,T=None,F=800000)
    outcome = app.led_num()
    print(f"0-100%可选离散电平数{outcome[0]},步长为:{outcome[1]}ms{outcome[1]*1000}us")
    print(app.cycle())
    run = app.count_steps(330)
    print(f"所需步数:{run}")


